package org.basis.netty.c5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * echo服务端
 *
 * @author Mr_wenpan@163.com 2021/09/18 17:55
 */
@Slf4j
public class EchoServer {

    public static void main(String[] args) {

        // boss组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // worker组
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);

        new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 连接建立后添加入站handler
                        pipeline.addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                // 如果收到client的消息，则给客户端回复
                                ByteBuf buf = (ByteBuf) msg;
                                log.info("接收到客户端的消息：{}", buf.toString(Charset.defaultCharset()));

                                // 创建一个bytebuf消息发送给客户端
                                // 建议使用ctx.alloc().buffer()来创建bytebuf
                                ByteBuf buffer = ctx.alloc().buffer();
                                System.out.println("类型：" + buffer.getClass());
                                buffer.writeBytes("hello client i am server".getBytes());

                                // 通过ctx来发送消息
                                ctx.writeAndFlush(buffer);

                                // 思考：需要释放 buffer 吗
                                // 思考：需要释放 response 吗

                                // 不再向下传递数据
//                                super.channelRead(ctx, msg);
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
